import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

import InvoiceType from '@/components/invoiceType';
import XforcePagination from '@xforceplus/pagination';
import { AuthCode, AuthCodeContext } from '@xforceplus/authcode';
import { Row, Col, Button, Select, Table, Icon, Modal, Popover, Checkbox } from 'antd';
import { getExpress, getsended, getPartSendParcel, getMergeSendParcel, getCancelSendGoods, getToSendList, getCountWait, resetState } from '../../module/action';
//------------------------------------------------
import DrawerStep2 from './DrawerStep2';
import ToSendCont from './ToSendCont';
import Opetation from '../Opetation'
import Footers from '../Footers';
//------------------------------------------------
import '../send.scss';
import './tosend.scss';

const confirm = Modal.confirm;

class ToSend extends Component {
  state = {
    selectedRowKeys: [],
    currentPage: 1, // 当前页
    defaultPageSize: 10, // 默认的每页条数, 默认值 10
    checkAll: false,//全选
    isAllChecked: false, // 是否当页全选
    indeterminate: false, // 是否部分选择
    checkedTotal: 0, // 已勾选数量, 默认值 0
    amountTotal: 0,//总数
    step_2_Visible: false,
    modalToSendVisible: false,//寄件
    // modalShowConFirm: false,//无需寄件
    confirmLoading: false,//loading
    LogisticsGoodsRequestParam: {},//查询条件
    goodsIdList: [],//物品id
    noSend: null,//防止网络慢，使得js异步执行时出现多个弹窗
    columns: [
      {
        title: '数量',
        dataIndex: 'goodsNumber',
        key: 'goodsNumber',
      }, {
        title: '收件单位',
        dataIndex: 'receiverCompanyName',
        key: 'receiverCompanyName',
      }, {
        title: '收件人',
        dataIndex: 'receiverName',
        key: 'receiverName',
      }, {
        title: '联系电话',
        dataIndex: 'receiverTel',
        key: 'receiverTel',
      }, {
        title: '收件地址',
        dataIndex: 'receiverAddr',
        key: 'receiverAddr',
      }
    ]
  }


  isEmptyObject(obj) {
    for (let key in obj) {
      return true;
    }
    return false;
  }
  componentWillReceiveProps(nextProps) {//父级props变化石调用
    const { sendedList, logisticsRequestParam, cancelSendGoods, orderParam } = nextProps
    const { checkAll, goodsIdList, currentPage, defaultPageSize, checkedTotal, modalToSendVisible, step_2_Visible, noSend } = this.state
    let that = this
    if (sendedList && sendedList.length === 1 && !cancelSendGoods.status && !step_2_Visible) {
      this.props.getMergeSendParcel({
        isAllSelect: checkAll ? 2 : 1,//全字段
        logisticsGoodsRequestParam: logisticsRequestParam,
        id: goodsIdList,
      })
      this.setState({
        step_2_Visible: true,
      });
    } else if (sendedList && sendedList.length > 1 && !cancelSendGoods.status && !modalToSendVisible) {
      this.setState({
        modalToSendVisible: true
      })
    } else if (cancelSendGoods.status && this.isEmptyObject(cancelSendGoods.list) && noSend === true) {
      this.setState({ noSend: false })
      confirm({
        title: '确认是否无需寄送？',
        content: <p className="modal-cont">
          当前勾选批次封面数量<span className="color-primary">{cancelSendGoods.list.coverCount}</span>个，
                    发票联<span className="color-primary">{cancelSendGoods.list.invoiceSheet1Count}</span>张，
                    抵扣联<span className="color-primary">{cancelSendGoods.list.invoiceSheet2Count}</span>张，
                    附件<span className="color-primary">{cancelSendGoods.list.attachmentCount}</span>个，
                    销货清单<span className="color-primary">{cancelSendGoods.list.salesBillCount}</span>个
                </p>,
        onOk() {
          that.props.getCancelSendGoods({
            id: goodsIdList,
            isAllSelect: checkAll ? 2 : 1,
            isCancel: 2,
            logisticsGoodsRequestParam: logisticsRequestParam,
          }, true)
          setTimeout(() => {
            that.props.getToSendList({
              logisticsGoodsRequestParam: logisticsRequestParam,
              orderParam: orderParam,
              pageParam: {
                pageIndex: currentPage,
                pageRowCount: defaultPageSize
              }
            })
            that.props.getCountWait(logisticsRequestParam)
            that.setState({
              selectedRowKeys: [],
              checkedTotal: 0,
              checkAll: false,
              isAllChecked: false,
              noSend: false,
            })
          }, 0);
        },
        onCancel() {
          that.props.resetState()
          that.setState({
            noSend: false
          })
        },
      });
    }
  }
  partOrmerge = (boolean, param) => {
    if (boolean) {
      this.props.getMergeSendParcel(param)
    } else {
      this.props.getPartSendParcel(param)
    }
  }
  sendHandler = (boolean) => {//第二步
    const { checkAll, goodsIdList } = this.state
    const { logisticsRequestParam, orderParam } = this.props
    // console.log(`logisticsRequestParam====`, logisticsRequestParam)
    if (checkAll) {
      const param = {
        isAllSelect: 2,//全字段
        logisticsGoodsRequestParam: logisticsRequestParam,
        orderParam: orderParam,
        id: [],
      }
      this.partOrmerge(boolean, param)
    } else {
      const param = {
        isAllSelect: 1,
        id: goodsIdList,
        logisticsGoodsRequestParam: logisticsRequestParam,
      }
      this.partOrmerge(boolean, param)
    }
    this.props.getExpress()
    this.setState({
      step_2_Visible: true,
      modalToSendVisible: false,
    });
  }
  onCloseDrawerStep_2 = () => {//第二步返回
    this.setState({
      step_2_Visible: false,
    });
  }
  showToSendModal = () => {//寄件弹窗
    const { goodsIdList, checkAll } = this.state
    const { logisticsRequestParam } = this.props
    this.props.getExpress()
    this.props.getsended({
      id: goodsIdList,
      isAllSelect: checkAll ? 2 : 1,
      logisticsGoodsRequestParam: logisticsRequestParam,
    })
  }
  showConfirm = () => {//无需寄送弹窗
    const { checkAll, goodsIdList } = this.state
    const { logisticsRequestParam } = this.props
    this.setState({
      noSend: true
    })
    this.props.getCancelSendGoods({
      id: goodsIdList,
      isAllSelect: checkAll ? 2 : 1,
      isCancel: 1,
      logisticsGoodsRequestParam: logisticsRequestParam,
      // orderParam: orderParam
    }, false)
  }
  cancelModal = () => {//弹窗取消按钮
    this.setState({
      modalToSendVisible: false,
    })
  }
  // 全选操作 返回值 true or false
  onCheckAllChange = (boolean) => {
    const { toSendList, countWait } = this.props
    if (typeof boolean === 'boolean') {
      const goodsIdList = []
      toSendList.map(item => {
        goodsIdList.push(item.id)
      })
      this.setState({
        checkAll: false,//总全选
        indeterminate: false,//部分全选
        isAllChecked: boolean, // 当页全选
        amountTotal: 0,
        selectedRowKeys: boolean ? toSendList.map(item => item.id) : [],
        checkedTotal: boolean ? toSendList.length : 0,
        goodsIdList: goodsIdList,
      });
    } else {
      // console.log(`onCheckAllChange:`, boolean.target.checked)
      this.setState({
        indeterminate: false,//部分全选
        checkAll: boolean.target.checked,//总全选
        isAllChecked: boolean.target.checked, // 当页全选
        amountTotal: boolean.target.checked ? parseInt(countWait.waitSend) : 0,
        selectedRowKeys: boolean.target.checked ? toSendList.map(item => item.id) : [],
        checkedTotal: boolean.target.checked ? toSendList.length : 0,
      });
    }
  };
  //当页部分选中操作
  partRowKeys = (selectedRowKeys, selectedRows) => {
    const goodsIdList = []
    selectedRows.map(item => {
      goodsIdList.push(item.id)
    })
    const { toSendList } = this.props
    this.setState({
      checkAll: false,
      amountTotal: 0,
      selectedRowKeys: selectedRowKeys,
      checkedTotal: selectedRowKeys.length,
      isAllChecked: selectedRowKeys.length === toSendList.length,
      goodsIdList: goodsIdList,
      step_2_Visible: false,
      modalToSendVisible: false
    })
  }
  changePage = (page, pageSize) => {
    // console.log('-------->', page, pageSize)
    this.setState({
      currentPage: page,
      defaultPageSize: pageSize,
      modalToSendVisible: false,
      step_2_Visible: false,
    })
  }

  render() {
    const { toSendList, sendedList, cancelSendGoods, userReSource } = this.props;
    const { columns, step_2_Visible, modalToSendVisible, modalShowConFirm, confirmLoading, checkAll, amountTotal, selectedRowKeys, isAllChecked, indeterminate, checkedTotal, currentPage, defaultPageSize } = this.state
    const record = {
      selectedRowKeys,
      amountTotal,
      checkAll,
      isAllChecked,
      indeterminate,
      checkedTotal,
      currentPage,
      defaultPageSize,
      onCheckAllChange: this.onCheckAllChange,
      partRowKeys: this.partRowKeys,
      changePage: this.changePage
    }
    const content = (
      <div>
        <p>合并寄送：全部物品寄送到同一个地址</p>
        <p>分开寄送：所选物品分别寄送到不同的地址</p>
        <p>返回重选：取消当前操作，返回重新选择物品</p>
      </div>
    );
    const pageParam = {
      pageIndex: currentPage,
      pageRowCount: defaultPageSize
    }
    const boolean = selectedRowKeys.length > 0 ? false : true
    const btmRight = <React.Fragment>
      <Button disabled={boolean} onClick={this.showConfirm}>无需寄送</Button>
      <Button disabled={boolean} onClick={this.showToSendModal} type="primary">寄送</Button>
      {/* <AuthCodeContext.Provider value={{ "authCodes": userReSource }}>
        <AuthCode auth_code={'X00501001'}>
          <Button disabled={boolean} onClick={this.showConfirm}>无需寄送</Button>
        </AuthCode>
        <AuthCode auth_code={'X00501002'}>
          <Button disabled={boolean} onClick={this.showToSendModal} type="primary">寄送</Button>
        </AuthCode>
      </AuthCodeContext.Provider> */}
    </React.Fragment>
    const btmLeft = <React.Fragment>
      <Checkbox
        indeterminate={checkAll}
        onChange={this.onCheckAllChange}
        checked={checkAll}>
        全部全选共{amountTotal}条数据
      </Checkbox>
    </React.Fragment>
    return (
      <React.Fragment>
        <Opetation pageParam={pageParam} />
        <ToSendCont record={record} />
        <Footers btmLeft={btmLeft} btmRight={btmRight} />
        <Modal
          title={<div><strong>寄送</strong><span className="tosend-modal-title-color">（您勾选的物品中包含多个不同收件方信息，请根据实际需要选择正确的操作方式）</span></div>}
          width="800px"
          visible={modalToSendVisible}
          onCancel={this.cancelModal}
          footer={
            <div>
              <Popover placement="topLeft" content={content} arrowPointAtCenter>
                <span className="tosend-modal-footer-tip">!</span>
              </Popover>
              <Button onClick={this.cancelModal}>返回</Button>
              <Button onClick={() => { this.sendHandler(true) }}>合并寄送</Button>
              <Button type="primary" onClick={() => { this.sendHandler(false) }}>分开寄送</Button>
            </div>}
          wrapClassName="modal-tosend">
          {sendedList && <Table rowKey="id" scroll={{ y: 120 }} pagination={false} columns={columns} dataSource={sendedList} />}

        </Modal>

        {step_2_Visible &&
          <DrawerStep2
            visible={step_2_Visible}
            dataSource={"message1"}
            onClose={this.onCloseDrawerStep_2} />
        }
      </React.Fragment>
    );
  }
};

function mapStateToProps(state) {
  const { sendLine, countWait, toSendList, sendedList, logisticsRequestParam, orderParam, cancelSendGoods, userReSource } = state.logistics;
  return {
    sendLine,
    countWait,
    toSendList,
    sendedList,
    orderParam,//排序条件
    logisticsRequestParam,//筛选条件
    cancelSendGoods,//无需寄送
    userReSource,//用户资源码
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({
    getExpress,//获取物流
    getsended,//寄件返回参数
    getPartSendParcel,//(分开)寄送接口
    getMergeSendParcel,//(合并)寄送接口
    getCancelSendGoods,//无需寄送接口
    getToSendList,//待寄送列表
    getCountWait,//待寄送总数
    resetState,//重置状态
  }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(ToSend);
